package com.phychips.common;

import java.io.BufferedWriter;
import java.io.FileWriter;

import android.annotation.SuppressLint;

import com.phychips.common.OnBytesAvailableListener;
//import com.phychips.rcp.RcpException;
//import com.phychips.rcp.RcpLib;
//import com.phychips.rcp.RcpPacket;
import com.phychips.rcp.RcpException;
import com.phychips.rcp.iCustomLogger;

public abstract class ReaderIo {
    public enum logType {
        CMD,
        RSP
    }

    static private boolean logmode = false;
    static private BufferedWriter log = null;

    public abstract void open() throws RcpException;

    public abstract void close() throws RcpException;

    public abstract void TransmitData(byte[] data, int length)
            throws RcpException;

    public abstract void setOnBytesAvailableListener(
            OnBytesAvailableListener listener);

    static private iCustomLogger customLogger;

    public static void setOnRcpLogListner(iCustomLogger logger) {
        customLogger = logger;
    }

    public static void log_start(String newlog) throws Exception {
        logmode = true;

        if (log != null) {
            log.close();
        }

        log = new BufferedWriter(new FileWriter(newlog));
    }

    public static void log_stop() throws Exception {
        logmode = false;

        if (log != null) {
            log.close();
        }

        log = null;
    }

    @SuppressLint("DefaultLocale")
    public static void log_write(logType type, byte[] rcp) {
        if (logmode == true) {
            try {
                StringBuffer sb = new StringBuffer();

                for (int i = 0; i < rcp.length; i++) {
                    sb.append(Integer.toHexString((rcp[i] & 0xff) + 0x100)
                            .substring(1).toUpperCase());
                }

                if (type == logType.CMD) {
                    log.write("CMD: " + sb.toString());
                } else {
                    log.write("RSP: " + sb.toString());
                }
                log.newLine();
                log.flush();
            } catch (Exception e) {
                logmode = false;
                e.printStackTrace();
            }
        }

        if (customLogger != null) {
            if (type == logType.CMD) {
                customLogger.onRcpTxReceived(rcp);
            } else {
                customLogger.onRcpRxReceived(rcp);
            }
        }
    }
}
